<template>
  <view class="resume-container">

    <!-- 上传图片区域 -->
    <view class="upload-section">
      <view class="upload-placeholder" @click="chooseModelCard">
        <image class="upload-icon" src="/static/logo.png" mode="aspectFit"></image>
        <text class="upload-text">上传模卡</text>
      </view>
    </view>

    <!-- 上传信息表单 -->
    <view class="resume-form">
      <text class="section-title">上传信息</text>

      <!-- 头像 -->
      <view class="form-item required">
        <text class="label">头像</text>
        <view class="avatar-wrapper">
          <view class="avatar-container">
            <image 
              class="avatar-preview" 
              :src="avatarUrl || '/static/logo.png'" 
              mode="aspectFill"
              @click="chooseAvatar"
            ></image>
          </view>
        </view>
      </view>

      <!-- 姓名 -->
      <view class="form-item required">
        <text class="label">姓名</text>
        <view class="input-wrapper">
          <input 
            type="text" 
            placeholder="请输入姓名" 
            v-model="formData.name" 
            class="form-input" 
            maxlength="40"
          />
        </view>
      </view>

      <!-- 性别 -->
      <view class="form-item required">
        <text class="label">性别</text>
        <view class="input-wrapper">
          <picker 
            mode="selector" 
            :range="genderOptions" 
            @change="onGenderChange"
            class="form-picker"
          >
            <view class="picker-text">
              {{ formData.gender || '请选择性别' }}
            </view>
          </picker>
        </view>
      </view>

    <!-- 角色类别 - 使用官方picker组件 -->
    <view class="form-item required">
      <text class="label">角色类别</text>
      <view class="input-wrapper">
        <picker 
          mode="multiSelector" 
          :range="rolePickerData" 
          :value="rolePickerValue"
          @change="onRolePickerChange"
          @columnchange="onRoleColumnChange"
          class="form-picker"
        >
          <view class="picker-text">
            {{ formData.roles && formData.roles.length > 0 ? formData.roles.join('、') : '请选择角色类别' }}
          </view>
        </picker>
      </view>
    </view>

      <!-- 地域 -->
      <view class="form-item required">
        <text class="label">地域</text>
        <view class="input-wrapper">
          <picker 
            mode="multiSelector" 
            :range="regionOptions" 
            @change="onRegionChange"
            @columnchange="onRegionColumnChange"
            class="form-picker"
          >
            <view class="picker-text">
              {{ formData.location || '请选择地域' }}
            </view>
          </picker>
        </view>
      </view>

      <!-- 身高 -->
      <view class="form-item required">
        <text class="label">身高</text>
        <view class="input-wrapper">
          <input 
            type="digit" 
            placeholder="请输入身高(cm)" 
            v-model="formData.height" 
            class="form-input" 
            @input="onHeightInput"
          />
          <text class="unit-text">cm</text>
        </view>
      </view>

      <!-- 体重 -->
      <view class="form-item required">
        <text class="label">体重</text>
        <view class="input-wrapper">
          <input 
            type="digit" 
            placeholder="请输入体重(kg)" 
            v-model="formData.weight" 
            class="form-input" 
            @input="onWeightInput"
          />
          <text class="unit-text">kg</text>
        </view>
      </view>

      <!-- 三围 -->
      <view class="form-item required">
        <text class="label">三围</text>
        <view class="input-wrapper">
          <view class="measurements-selector" @click="toggleMeasurementsPopup">
            <text class="measurements-display">
              {{ formData.measurements || '请选择三围' }}
            </text>
            <text class="measurements-arrow">▼</text>
          </view>
        </view>
      </view>

      <!-- 三围弹窗 -->
      <view class="measurements-popup-mask" v-if="showMeasurementsPopup" @click="toggleMeasurementsPopup">
        <view class="measurements-popup" @click.stop>
          <view class="measurements-popup-header">
            <text class="measurements-popup-title">输入三围</text>
          </view>
          <view class="measurements-input-group">
            <view class="measurements-input-item">
              <text class="measurements-label">胸围</text>
              <input 
                type="digit" 
                placeholder="请输入胸围" 
                v-model="measurementsData.bust" 
                class="measurements-input"
                @input="onBustInput"
              />
              <text class="measurements-unit">cm</text>
            </view>
            <view class="measurements-input-item">
              <text class="measurements-label">腰围</text>
              <input 
                type="digit" 
                placeholder="请输入腰围" 
                v-model="measurementsData.waist" 
                class="measurements-input"
                @input="onWaistInput"
              />
              <text class="measurements-unit">cm</text>
            </view>
            <view class="measurements-input-item">
              <text class="measurements-label">臀围</text>
              <input 
                type="digit" 
                placeholder="请输入臀围" 
                v-model="measurementsData.hips" 
                class="measurements-input"
                @input="onHipsInput"
              />
              <text class="measurements-unit">cm</text>
            </view>
          </view>
          <view class="measurements-btn-group">
            <button size="mini" type="default" @click="toggleMeasurementsPopup" class="measurements-btn">取消</button>
            <button size="mini" type="primary" @click="confirmMeasurements" class="measurements-btn">确定</button>
          </view>
        </view>
      </view>

      <!-- 鞋码 -->
      <view class="form-item">
        <text class="label">鞋码</text>
        <view class="input-wrapper">
          <input type="text" placeholder="请输入鞋码" v-model="formData.shoeSize" class="form-input" />
        </view>
      </view>

      <!-- 个人简介 -->
      <view class="form-item">
        <text class="label">个人简介</text>
        <view class="textarea-wrapper">
          <textarea placeholder="请输入个人介绍" v-model="formData.introduction" class="form-textarea"></textarea>
        </view>
      </view>

      <!-- 上传图片 -->
      <view class="form-item">
        <text class="label">上传图片</text>
        <view class="upload-images">
          <view 
            v-for="(image, index) in images" 
            :key="index" 
            class="image-preview"
            @click="previewImage(index)"
          >
            <image :src="image" mode="aspectFill"></image>
            <view class="delete-btn" @click.stop="deleteImage(index)">×</view>
          </view>
          <view 
            v-if="images.length < 9" 
            class="upload-image-btn" 
            @click="chooseImages"
          >
            <text class="upload-icon-text">+</text>
          </view>
        </view>
      </view>

      <!-- 上传视频 -->
      <view class="form-item required">
        <text class="label">上传视频</text>
        <view class="upload-images">
          <view 
            v-for="(video, index) in videos" 
            :key="index" 
            class="uploaded-item"
          >
            <image 
              class="uploaded-preview" 
              :src="video.thumbTempFilePath || '/static/logo.png'" 
              mode="aspectFill"
            ></image>
            <text class="video-duration">{{ formatDuration(video.duration) }}</text>
            <view class="delete-btn" @click.stop="deleteVideo(index)">×</view>
          </view>
          <view 
            v-if="videos.length < 1" 
            class="upload-image-btn" 
            @click="chooseVideo"
          >
            <text class="upload-icon-text">+</text>
          </view>
        </view>
      </view>

      <!-- 上传模卡 -->
      <view class="form-item required">
        <text class="label">上传模卡</text>
        <view class="upload-images">
          <view 
            v-if="modelCard" 
            class="model-card-preview"
            @click="previewModelCard"
          >
            <image :src="modelCard" mode="aspectFill"></image>
            <view class="delete-btn" @click.stop="deleteModelCard">×</view>
          </view>
          <view 
            v-if="!modelCard" 
            class="upload-image-btn" 
            @click="chooseModelCard"
          >
            <text class="upload-icon-text">+</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="footer-buttons">
      <button class="btn btn-outline" @click="saveToLocal">暂存</button>
      <button class="btn btn-primary" @click="saveForm">保存资料</button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'
import StorageUtil from '/pages/utils/storage.js'

/* ---------------- 角色多选相关 ---------------- */
// 角色选择器数据
const roleOptions = ['礼仪', '兼职', '带队'];
const rolePickerData = ref([
  roleOptions, // 第一列：所有角色选项
  roleOptions  // 第二列：所有角色选项（用于多选）
]);

const rolePickerValue = ref([0, 0]); // 默认选中第一列第一个

// 角色选择器变化
const onRolePickerChange = (e) => {
  const [firstIndex, secondIndex] = e.detail.value;
  const selectedRoles = [];
  
  // 收集选中的角色（去重）
  if (firstIndex !== undefined) {
    selectedRoles.push(roleOptions[firstIndex]);
  }
  if (secondIndex !== undefined && secondIndex !== firstIndex) {
    selectedRoles.push(roleOptions[secondIndex]);
  }
  
  formData.roles = selectedRoles;
};

// 列变化处理
const onRoleColumnChange = (e) => {
  // 可以在这里添加特殊逻辑
};


const userStore = useUserStore()

// 头像URL
const avatarUrl = ref('');

// 表单数据
const formData = reactive({
  name: '',
  gender: '',
  location: '',
  height: '',
  weight: '',
  measurements: '',
  shoeSize: '',
  introduction: '',
  roles: [] // 新增角色字段
});

// 性别选项
const genderOptions = ref(['男', '女']);




// 性别选择器变化
const onGenderChange = (e) => {
  formData.gender = genderOptions.value[e.detail.value];
};

// 输入验证方法
const validateInput = (value, type) => {
  if (type === 'name') {
    return value.length > 0 && value.length <= 40;
  }
  if (type === 'height') {
    return value.length > 0 && value.length <= 300; // 假设身高范围在0-300cm
  }
  if (type === 'weight') {
    return value.length > 0 && value.length <= 200; // 假设体重范围在0-200kg
  }
  return true;
};

// 输入身高时触发
const onHeightInput = (e) => {
  const value = e.detail.value;
  if (validateInput(value, 'height')) {
    formData.height = value;
  } else {
    formData.height = value.slice(0, -1); // 删除最后一个字符
  }
};

// 输入体重时触发
const onWeightInput = (e) => {
  const value = e.detail.value;
  if (validateInput(value, 'weight')) {
    formData.weight = value;
  } else {
    formData.weight = value.slice(0, -1); // 删除最后一个字符
  }
};


// 省市联动数据
const provinceCityData = {
  '北京市': ['北京市'],
  '天津市': ['天津市'],
  '河北省': ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'],
  '山西省': ['太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'],
  '内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市', '兴安盟', '锡林郭勒盟', '阿拉善盟'],
  '辽宁省': ['沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'],
  '吉林省': ['长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市', '延边朝鲜族自治州'],
  '黑龙江省': ['哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市', '大兴安岭地区'],
  '上海市': ['上海市'],
  '江苏省': ['南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'],
  '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'],
  '安徽省': ['合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市'],
  '福建省': ['福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'],
  '江西省': ['南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'],
  '山东省': ['济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市'],
  '河南省': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市'],
  '湖北省': ['武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市', '恩施土家族苗族自治州', '仙桃市', '潜江市', '天门市', '神农架林区'],
  '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市', '湘西土家族苗族自治州'],
  '广东省': ['广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'],
  '广西壮族自治区': ['南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'],
  '海南省': ['海口市', '三亚市', '三沙市', '儋州市', '五指山市', '琼海市', '文昌市', '万宁市', '东方市', '定安县', '屯昌县', '澄迈县', '临高县', '白沙黎族自治县', '昌江黎族自治县', '乐东黎族自治县', '陵水黎族自治县', '保亭黎族苗族自治县', '琼中黎族苗族自治县'],
  '重庆市': ['重庆市'],
  '四川省': ['成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '阿坝藏族羌族自治州', '甘孜藏族自治州', '凉山彝族自治州'],
  '贵州省': ['贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市', '黔西南布依族苗族自治州', '黔东南苗族侗族自治州', '黔南布依族苗族自治州'],
  '云南省': ['昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市', '楚雄彝族自治州', '红河哈尼族彝族自治州', '文山壮族苗族自治州', '西双版纳傣族自治州', '大理白族自治州', '德宏傣族景颇族自治州', '怒江傈僳族自治州', '迪庆藏族自治州'],
  '西藏自治区': ['拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区'],
  '陕西省': ['西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'],
  '甘肃省': ['兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市', '临夏回族自治州', '甘南藏族自治州'],
  '青海省': ['西宁市', '海东市', '海北藏族自治州', '黄南藏族自治州', '海南藏族自治州', '果洛藏族自治州', '玉树藏族自治州', '海西蒙古族藏族自治州'],
  '宁夏回族自治区': ['银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'],
  '新疆维吾尔自治区': ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市', '昌吉回族自治州', '博尔塔拉蒙古自治州', '巴音郭楞蒙古自治州', '阿克苏地区', '克孜勒苏柯尔克孜自治州', '喀什地区', '和田地区', '伊犁哈萨克自治州', '塔城地区', '阿勒泰地区'],
  '台湾省': ['台北市', '新北市', '桃园市', '台中市', '台南市', '高雄市', '基隆市', '新竹市', '嘉义市', '新竹县', '苗栗县', '彰化县', '南投县', '云林县', '嘉义县', '屏东县', '宜兰县', '花莲县', '台东县', '澎湖县', '金门县', '连江县'],
  '香港特别行政区': ['香港岛', '九龙', '新界'],
  '澳门特别行政区': ['澳门半岛', '氹仔', '路环']
};

// 获取省份列表
const provinces = Object.keys(provinceCityData);

// 地域选项 - 用于多级选择器
const regionOptions = ref([
  provinces,  // 第一列：省份
  provinceCityData[provinces[0]]  // 第二列：默认显示第一个省的城市
]);

// 本地暂存数据
const setLocalData = async () => {

}

// 将本地文件路径转换为Base64（微信小程序/APP端）
const fileToBase64 = (filePath, mimeType = '') => {
  return new Promise((resolve, reject) => {
    try {
      const fsm = typeof uni.getFileSystemManager === 'function' ? uni.getFileSystemManager() : null;
      if (!fsm || typeof fsm.readFile !== 'function') {
        reject(new Error('当前环境不支持文件读取'));
        return;
      }

      fsm.readFile({
        filePath,
        encoding: 'base64',
        success: (res) => {
          const prefix = mimeType ? `data:${mimeType};base64,` : 'data:;base64,';
          resolve(prefix + res.data);
        },
        fail: (err) => reject(err)
      });
    } catch (e) {
      reject(e);
    }
  });
};

// 地域选择器变化
const onRegionChange = (e) => {
  const [provinceIndex, cityIndex] = e.detail.value;
  const province = regionOptions.value[0][provinceIndex];
  const city = regionOptions.value[1][cityIndex];
  formData.location = `${province} ${city}`;
};

// 地域选择器列变化 - 处理省市联动
const onRegionColumnChange = (e) => {
  const { column, value } = e.detail;
  if (column === 0) {
    // 省份改变时，更新对应的城市列表
    const province = regionOptions.value[0][value];
    regionOptions.value[1] = provinceCityData[province];
  }
};

// 图片预览
const images = ref([]);

// 上传模卡图片URL
const modelCard = ref('');

// 视频预览
const videos = ref([]);

// 选择头像方法
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1, // 最多选择1张图片
    sizeType: ['compressed'], // 压缩图片
    sourceType: ['album', 'camera'], // 从相册选择或拍照
    success: (res) => {
      console.log('选择头像成功:', res);
      // 更新头像URL
      avatarUrl.value = res.tempFilePaths[0];
      
      // 显示成功提示
      uni.showToast({
        title: '头像选择成功',
        icon: 'success',
        duration: 1500
      });
    },
    fail: (err) => {
      console.error('选择头像失败:', err);
    }
  });
};

// 选择多张图片
const chooseImages = () => {
  uni.chooseImage({
    count: 9 - images.value.length, // 最多选择9 - 已选数量张图片
    sizeType: ['compressed'], // 压缩图片
    sourceType: ['album', 'camera'], // 从相册选择或拍照
    success: (res) => {
      console.log('选择图片成功:', res);
      images.value = [...images.value, ...res.tempFilePaths];
    },
    fail: (err) => {
      console.error('取消选择图片:', err);
    }
  });
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    urls: images.value,
    current: images.value[index]
  });
};

// 删除图片
const deleteImage = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        images.value.splice(index, 1);
      }
    }
  });
};

// 选择上传模卡图片
const chooseModelCard = () => {
  uni.chooseImage({
    count: 1, // 最多选择1张图片
    sizeType: ['compressed'], // 压缩图片
    sourceType: ['album', 'camera'], // 从相册选择或拍照
    success: (res) => {
      console.log('选择模卡图片成功:', res);
      modelCard.value = res.tempFilePaths[0];
    },
    fail: (err) => {
      console.error('取消模卡图片:', err);
    }
  });
};

// 预览上传模卡图片
const previewModelCard = () => {
  uni.previewImage({
    urls: [modelCard.value],
    current: modelCard.value
  });
};

// 删除上传模卡图片
const deleteModelCard = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张模卡图片吗？',
    success: (res) => {
      if (res.confirm) {
        modelCard.value = '';
      }
    }
  });
};

// 选择视频
const chooseVideo = () => {
  uni.chooseVideo({
    count: 1, // 最多选择1个视频
    sourceType: ['album', 'camera'], // 从相册选择或拍照
    success: (res) => {
      console.log('选择视频成功:', res);
      videos.value = [{
        url: res.tempFilePath,
        thumbTempFilePath: res.tempThumbPath,
        duration: res.duration
      }];
    },
    fail: (err) => {
      console.error('取消选择视频:', err);
    }
  });
};

// 预览视频
const previewVideo = (index) => {
  uni.navigateTo({
    url: `/pages/video-player/video-player?url=${videos.value[index].url}`
  });
};

// 删除视频
const deleteVideo = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这段视频吗？',
    success: (res) => {
      if (res.confirm) {
        videos.value.splice(index, 1);
      }
    }
  });
};

// 格式化视频时长
const formatDuration = (duration) => {
  const minutes = Math.floor(duration / 60);
  const seconds = Math.floor(duration % 60);
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
};

// 上传进度状态
const uploadProgress = ref({
  show: false,
  current: 0,
  total: 0,
  message: '正在上传文件...'
});

// 更新上传进度
const updateUploadProgress = (current, total, message) => {
  uploadProgress.value = {
    show: true,
    current,
    total,
    message
  };
  
  uni.showLoading({
    title: `${message} (${current}/${total})`,
    mask: true
  });
};

// 1) 单文件上传封装：返回 fileUrl
const uploadFileAndGetUrl = (filePath, directory = 'resume') => {
  console.log("上传文件", filePath, directory);
  
  return new Promise((resolve, reject) => {
    const task = uni.uploadFile({
      url: 'https://api.shmodio.cn/alioss',
      filePath,
      name: 'file',
      formData: { directory },
      success: (res) => {
        try {
          console.log("上传文件成功", res);
          
          const data = JSON.parse(res.data);
          const url = data?.data?.fileUrl || data?.url;
          if (url) return resolve(url);
          reject(new Error(data?.message || '上传失败'));
        } catch {
          reject(new Error('响应解析失败'));
        }
      },
      fail: reject
    });
  });
};

/**
 * 并发上传多图，返回成功上传的 url 数组
 * @param {Array<String>} filePaths  临时路径数组
 * @param {String} directory         上传目录
 * @returns {Promise<Array<String>>} 成功 url 数组
 */
 const uploadFilesSimple = async (filePaths, directory = 'images') => {
  if (!Array.isArray(filePaths) || !filePaths.length) return []

  // 每个路径映射成一个 Promise
  const tasks = filePaths.map(path => uploadFileAndGetUrl(path, directory))

  // 等待全部完成（无论成功失败）
  const results = await Promise.allSettled(tasks)

  // 只取成功的 url
  return results
    .filter(r => r.status === 'fulfilled')
    .map(r => r.value)
}


// 2) 各类素材上传（可在选择完后立刻传，也可在保存前统一传）
const uploadAllAssets = async () => {
  console.log("调用uploadAllAssets方法中");
  console.log("avatarUrl.value", avatarUrl.value);
  console.log("images.value", images.value);
  console.log("modelCard.value", modelCard.value);
  console.log("videos.value", videos.value);
  
  // 头像
  if (avatarUrl.value) {
    console.log("上传头像", avatarUrl.value);
    
    avatarUrl.value = await uploadFileAndGetUrl(avatarUrl.value, 'avatar');
    console.log('avatarUrl.value', avatarUrl.value);
  }

  // 多图并发 - 修复：添加 await 等待上传完成
  if (images.value.length) {
    console.log('上传多图');
    console.log('images.value', images.value);

    const uploadedImageUrls = await uploadFilesSimple(images.value, 'images');
    images.value = uploadedImageUrls;
    console.log('上传多图完成，新URLs:', images.value);
  }

  // 模卡
  if (modelCard.value ) {
    console.log("上传模卡");
    
    modelCard.value = await uploadFileAndGetUrl(modelCard.value, 'modelcard');
    console.log('modelCard.value', modelCard.value);
  }

  // 视频（如有封面）
  if (videos.value.length) {
    console.log("上传视频");
    
    for (let i = 0; i < videos.value.length; i++) {
      const video = videos.value[i];
      let uploadedVideoUrl = video.url;
      let uploadedThumbUrl = video.thumbTempFilePath;

      // 上传视频文件
      if (video.url ) {
        uploadedVideoUrl = await uploadFileAndGetUrl(video.url, 'videos');
        console.log('uploadedVideoUrl', uploadedVideoUrl);
      }

      // 上传视频缩略图
      if (video.thumbTempFilePath ) {
        uploadedThumbUrl = await uploadFileAndGetUrl(video.thumbTempFilePath, 'videos-thumb');
        console.log('uploadedThumbUrl', uploadedThumbUrl);
      }

      videos.value[i] = {
        url: uploadedVideoUrl,
        thumbTempFilePath: uploadedThumbUrl,
        duration: video.duration
      };
    }
  }
  console.log("上传所有素材完成");
  
};

// 3) 保存：把 URL 带入表单
const saveForm = async () => {
  try {
    // 校验必填项
    if (!formData.name) {
      uni.showToast({
        title: '请输入姓名',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.gender) {
      uni.showToast({
        title: '请选择性别',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.roles || formData.roles.length === 0) {
      uni.showToast({
        title: '请选择角色类别',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.location) {
      uni.showToast({
        title: '请选择地域',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.height) {
      uni.showToast({
        title: '请输入身高',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.weight) {
      uni.showToast({
        title: '请输入体重',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    if (!formData.measurements) {
      uni.showToast({
        title: '请输入三围',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    uni.showLoading({
      title: '正在保存数据...',
      mask: true
    });
    console.log("开始上传所有素材");
    
    // 先上传所有素材，拿到可访问的 URL
    await uploadAllAssets();

    const saveData = {
      name: formData.name,
      gender: formData.gender,
      location: formData.location,
      height: formData.height,
      weight: formData.weight,
      measurements: formData.measurements,
      shoeSize: formData.shoeSize,
      introduction: formData.introduction,
      roles: formData.roles,
      avatar: avatarUrl.value,
      images: images.value,
      modelCard: modelCard.value,
      videos: videos.value,
      rowid: userStore.rowid
    };

    console.log('saveData', saveData);
    

    const res = await apiService.upload(saveData);

    uni.hideLoading();
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000
    });

    // 清除暂存数据
    StorageUtil.remove('resume_draft');

    // 设置刷新标记，通知简历库页面需要刷新
    uni.setStorageSync('refreshResumeList', true);

    setTimeout(() => {
      uni.navigateBack();
    }, 2000);
  } catch (error) {
    uni.hideLoading();
    console.error('保存失败:', error);
    uni.showToast({
      title: error.message || '保存失败，请重试',
      icon: 'none',
      duration: 2000
    });
  }
};

/* ---------------- 三围弹窗相关 ---------------- */
const showMeasurementsPopup = ref(false);
const measurementsData = reactive({
  bust: '',
  waist: '',
  hips: ''
});

// 切换三围弹窗显示状态
const toggleMeasurementsPopup = () => {
  showMeasurementsPopup.value = !showMeasurementsPopup.value;
  // 如果弹窗打开，解析当前三围数据
  if (showMeasurementsPopup.value && formData.measurements) {
    const parts = formData.measurements.split('-');
    if (parts.length === 3) {
      measurementsData.bust = parts[0];
      measurementsData.waist = parts[1];
      measurementsData.hips = parts[2];
    }
  }
};

// 胸围输入验证
const onBustInput = (e) => {
  const value = e.detail.value;
  const numericValue = value.replace(/[^\d.]/g, '');
  const parts = numericValue.split('.');
  if (parts.length > 1) {
    measurementsData.bust = parts[0] + '.' + parts[1].substring(0, 2);
  } else {
    measurementsData.bust = numericValue;
  }
};

// 腰围输入验证
const onWaistInput = (e) => {
  const value = e.detail.value;
  const numericValue = value.replace(/[^\d.]/g, '');
  const parts = numericValue.split('.');
  if (parts.length > 1) {
    measurementsData.waist = parts[0] + '.' + parts[1].substring(0, 2);
  } else {
    measurementsData.waist = numericValue;
  }
};

// 臀围输入验证
const onHipsInput = (e) => {
  const value = e.detail.value;
  const numericValue = value.replace(/[^\d.]/g, '');
  const parts = numericValue.split('.');
  if (parts.length > 1) {
    measurementsData.hips = parts[0] + '.' + parts[1].substring(0, 2);
  } else {
    measurementsData.hips = numericValue;
  }
};

// 确认三围选择
const confirmMeasurements = () => {
  if (measurementsData.bust && measurementsData.waist && measurementsData.hips) {
    formData.measurements = `${measurementsData.bust}-${measurementsData.waist}-${measurementsData.hips}`;
  } else {
    formData.measurements = '';
  }
  toggleMeasurementsPopup();
};

// 暂存数据到本地存储
const saveToLocal = async () => {
  try {
    // 检查是否有需要上传的文件
    const hasFilesToUpload = (
      (avatarUrl.value && !avatarUrl.value.startsWith('http')) ||
      images.value.some(img => !img.startsWith('http')) ||
      videos.value.some(video => !video.url.startsWith('http')) ||
      (modelCard.value && !modelCard.value.startsWith('http'))
    );

    if (hasFilesToUpload) {
      uni.showLoading({
        title: '正在暂存...',
        mask: true
      });

      // 先上传所有素材到OSS，获取可访问的URL
      const uploadPromises = [];
      
      // 上传头像
      if (avatarUrl.value && !avatarUrl.value.startsWith('http')) {
        uploadPromises.push(
          uploadFileAndGetUrl(avatarUrl.value, 'avatar').then(url => {
            avatarUrl.value = url;
          })
        );
      }
      
      // 上传图片
      const imageUploads = images.value
        .filter(img => !img.startsWith('http'))
        .map(img => uploadFileAndGetUrl(img, 'images'));
      if (imageUploads.length > 0) {
        uploadPromises.push(
          Promise.all(imageUploads).then(urls => {
            const newImages = [...images.value];
            let urlIndex = 0;
            for (let i = 0; i < newImages.length; i++) {
              if (!newImages[i].startsWith('http')) {
                newImages[i] = urls[urlIndex++];
              }
            }
            images.value = newImages;
          })
        );
      }
      
      // 上传视频
      const videoUploads = videos.value
        .filter(video => !video.url.startsWith('http'))
        .map(async video => {
          const videoUrl = await uploadFileAndGetUrl(video.url, 'videos');
          const thumbUrl = video.thumbTempFilePath && !video.thumbTempFilePath.startsWith('http') 
            ? await uploadFileAndGetUrl(video.thumbTempFilePath, 'videos-thumb')
            : video.thumbTempFilePath;
          return { url: videoUrl, thumbTempFilePath: thumbUrl, duration: video.duration };
        });
      if (videoUploads.length > 0) {
        uploadPromises.push(
          Promise.all(videoUploads).then(uploadedVideos => {
            const newVideos = [...videos.value];
            let videoIndex = 0;
            for (let i = 0; i < newVideos.length; i++) {
              if (!newVideos[i].url.startsWith('http')) {
                newVideos[i] = uploadedVideos[videoIndex++];
              }
            }
            videos.value = newVideos;
          })
        );
      }
      
      // 上传模卡
      if (modelCard.value && !modelCard.value.startsWith('http')) {
        uploadPromises.push(
          uploadFileAndGetUrl(modelCard.value, 'modelcard').then(url => {
            modelCard.value = url;
          })
        );
      }
      
      // 等待所有上传完成
      await Promise.all(uploadPromises);
      
      uni.hideLoading();
    }
    
    // 保存到本地存储
    const resumeData = {
      formData: { ...formData },
      avatarUrl: avatarUrl.value,
      images: [...images.value],
      videos: [...videos.value],
      modelCard: modelCard.value,
      measurementsData: { ...measurementsData },
      roleChecked: [...roleChecked.value],
      timestamp: Date.now()
    };
    
    StorageUtil.set('resume_draft', resumeData);
    
    uni.showToast({
      title: '暂存成功',
      icon: 'success',
      duration: 1500
    });
  } catch (error) {
    uni.hideLoading();
    console.error('暂存失败:', error);
    uni.showToast({
      title: error.message || '暂存失败，请重试',
      icon: 'none',
      duration: 2000
    });
  }
};

// 从本地存储恢复数据
const loadFromLocal = () => {
  try {
    const savedData = StorageUtil.get('resume_draft');
    if (savedData && savedData.timestamp) {
      // 检查数据是否过期（7天）
      const isExpired = Date.now() - savedData.timestamp > 7 * 24 * 60 * 60 * 1000;
      if (isExpired) {
        StorageUtil.remove('resume_draft');
        return;
      }
      
      // 恢复表单数据
      if (savedData.formData) {
        Object.assign(formData, savedData.formData);
      }
      
      // 恢复其他数据
      if (savedData.avatarUrl) {
        avatarUrl.value = savedData.avatarUrl;
      }
      
      if (savedData.images) {
        images.value = [...savedData.images];
      }
      
      if (savedData.videos) {
        videos.value = [...savedData.videos];
      }
      
      if (savedData.modelCard) {
        modelCard.value = savedData.modelCard;
      }
      
      if (savedData.measurementsData) {
        Object.assign(measurementsData, savedData.measurementsData);
      }
      
      if (savedData.roleChecked) {
        roleChecked.value = [...savedData.roleChecked];
      }
      
      console.log('已恢复暂存数据');
    }
  } catch (error) {
    console.error('恢复暂存数据失败:', error);
  }
};

// 页面加载时恢复数据
onMounted(() => {
  loadFromLocal();
});

// 暂存按钮点击事件
const upLoad = () => {
  saveToLocal();
};

</script>

<style lang="scss" scoped>
.resume-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 80px;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  
  .page-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }
  
  .action-buttons {
    display: flex;
    align-items: center;
    
    .dot-menu {
      font-size: 18px;
      color: #333;
      margin-right: 15px;
    }
    
    .close-btn {
      font-size: 22px;
      color: #333;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.upload-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  
  .upload-placeholder {
    width: 100px;
    height: 100px;
    background-color: #f5f5f5;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    
    .upload-icon {
      width: 40px;
      height: 40px;
      margin-bottom: 5px;
    }
    
    .upload-text {
      font-size: 12px;
      color: #999;
      text-align: center;
      padding: 0 5px;
    }
  }
}

.resume-form {
  padding: 0 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 15px;
  }
  
  .form-item {
    display: flex;
    margin-bottom: 15px;
    padding: 10px;
    
    &.required {
      .label::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 2px;
      }
    }
    
    .label {
      width: 70px;
      font-size: 14px;
      color: #333;
      line-height: 40px;
    }
    
    .input-wrapper {
      flex: 1;
      height: 40px;
      background-color: #f9f9f9;
      border-radius: 20px;
      padding: 0 15px;
      display: flex;
      align-items: center;
    }
    
    .form-input {
      width: 100%;
      height: 100%;
      font-size: 14px;
      color: #333;
      background-color: transparent;
    }

    .form-picker {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 14px;
      color: #333;
      background-color: transparent;
      padding: 0;
    }

    .picker-text {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 14px;
      color: #333;
      background-color: transparent;
      padding: 0;
      
      &:empty::before {
        content: '请选择';
        color: #999;
      }
    }

    // 角色选择器样式
    .role-selector {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      cursor: pointer;
      
      .role-display {
        flex: 1;
        font-size: 14px;
        color: #333;
        
        &:empty::before {
          content: '请选择角色类别';
          color: #999;
        }
      }
      
      .role-arrow {
        font-size: 12px;
        color: #999;
        margin-left: 10px;
      }
    }
    
    .textarea-wrapper {
      flex: 1;
      background-color: #f9f9f9;
      border-radius: 10px;
      padding: 10px 15px;
      min-height: 100px;
    }
    
    .form-textarea {
      width: 100%;
      height: 80px;
      font-size: 14px;
      color: #333;
      background-color: transparent;
    }
    
    .upload-images {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      
      .image-preview {
        position: relative;
        width: 40px;
        height: 40px;
        border-radius: 5px;
        overflow: hidden;
        
        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .delete-btn {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 18px;
          z-index: 10;
        }
      }
      
      .upload-image-btn {
        width: 40px;
        height: 40px;
        background-color: #f9f9f9;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px dashed #999;
        
        .upload-icon-text {
          font-size: 24px;
          color: #999;
        }
      }

      .uploaded-item {
        position: relative;
        width: 40px;
        height: 40px;
        border-radius: 5px;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #f9f9f9;
        border: 1px dashed #999;

        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .video-duration {
          position: absolute;
          bottom: 0;
          right: 0;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          font-size: 10px;
          padding: 2px 5px;
          border-top-left-radius: 5px;
        }

        .delete-btn {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 18px;
          z-index: 10;
        }
      }

      .model-card-preview {
        position: relative;
        width: 40px;
        height: 40px;
        border-radius: 5px;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .delete-btn {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 18px;
          z-index: 10;
        }
      }
    }
    
    .avatar-wrapper {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      
      .avatar-container {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .avatar-preview {
          width: 30px;
          height: 30px;
          border-radius: 25px;
          background-color: #f0f0f0;
          cursor: pointer;
          transition: all 0.3s ease;
          
          &:active {
            transform: scale(0.95);
          }
          
          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }
        }
        
        .avatar-tip {
          position: absolute;
          bottom: -15px;
          left: 50%;
          transform: translateX(-50%);
          font-size: 10px;
          color: #999;
          background-color: #fff;
          padding: 2px 8px;
          border-radius: 5px;
          box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

// 角色弹窗样式
.role-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-popup {
  width: 80%;
  max-height: 60%;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .role-popup-header {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
    
    .role-popup-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }
  
  .role-list {
    flex: 1;
    max-height: 300px;
    
    .role-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: background-color 0.2s ease;
      
      &:hover {
        background-color: #f9f9f9;
      }
      
      &.checked {
        background-color: #f0f8ff;
        
        .check-icon {
          color: #1890ff;
        }
      }
      
      .role-item-text {
        font-size: 14px;
        color: #333;
      }
      
      .check-icon {
        font-size: 16px;
        color: #999;
        font-weight: bold;
      }
    }
  }
  
  .role-btn-group {
    padding: 15px;
    display: flex;
    gap: 10px;
    border-top: 1px solid #f0f0f0;
    
    .role-btn {
      flex: 1;
      height: 36px;
      border-radius: 18px;
      font-size: 14px;
    }
  }
}

// 三围选择器样式
.measurements-selector {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  
  .measurements-display {
    flex: 1;
    font-size: 14px;
    color: #333;
    
    &:empty::before {
      content: '请选择三围';
      color: #999;
    }
  }
  
  .measurements-arrow {
    font-size: 12px;
    color: #999;
    margin-left: 10px;
  }
}

// 三围弹窗样式
.measurements-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.measurements-popup {
  width: 85%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  .measurements-popup-header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
    
    .measurements-popup-title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }
  }
  
  .measurements-input-group {
    padding: 20px;
    
    .measurements-input-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      position: relative;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .measurements-label {
        width: 60px;
        font-size: 14px;
        color: #333;
        margin-right: 15px;
      }
      
      .measurements-input {
        flex: 1;
        height: 40px;
        background-color: #f9f9f9;
        border-radius: 20px;
        padding: 0 15px;
        font-size: 14px;
        color: #333;
        border: none;
        outline: none;
        padding-right: 40px;
      }
      
      .measurements-unit {
        position: absolute;
        right: 15px;
        font-size: 12px;
        color: #999;
        pointer-events: none;
      }
    }
  }
  
  .measurements-btn-group {
    padding: 20px;
    display: flex;
    gap: 15px;
    border-top: 1px solid #f0f0f0;
    
    .measurements-btn {
      flex: 1;
      height: 40px;
      border-radius: 20px;
      font-size: 14px;
    }
  }
}

.footer-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
  display: flex;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .btn {
    flex: 1;
    height: 45px;
    border-radius: 22.5px;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &.btn-outline {
      border: 1px solid #ddd;
      color: #333;
      margin-right: 10px;
    }
    
    &.btn-primary {
      background-color: #000;
      color: #fff;
    }
  }
}
</style>
